//
//  QRCodePreviewViewController.swift
//  app路由
//
//  Created by zhaoguoteng on 2020/5/1.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

import UIKit

class QRCodePreviewViewController: UIViewController {

    @IBOutlet var codeImgView: UIImageView!
    
    var qrText: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if let qrText = qrText {
            codeImgView.image = qrCodeImg(qrText)
        }
    }
    
    // 生成二维码
    func qrCodeImg(_ qrString: String) -> UIImage? {
        
        let qrData = qrString.data(using: .utf8)
        guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else {
            return nil
        }
        
        qrFilter.setValue(qrData, forKey: "inputMessage")
        qrFilter.setValue("H", forKey: "inputCorrectionLevel")
        
        guard let ciImage = qrFilter.outputImage else {
            return nil
        }
        
        let scale = 240.0 / ciImage.extent.size.width
        
        return UIImage(ciImage: ciImage.transformed(by: CGAffineTransform.init(scaleX: scale, y: scale)))
    }
}
